using System.Collections.Generic;
using LitJson2;
using Net.Common;
using UnityEngine;

/****************************************************
// 功能：
// | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
// | Copyright (c) 2021-2025 聊来 All rights reserved.
// | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">聊来</a> )
// | @Author: 贯彻己道的云 <18970881148@qq.com>
// | DateTime: 2025/3/5 16:13:9
*****************************************************/

public class RoomController : BaseController<RoomController>
{

    public RoomWindow roomWindow;
    
    public override void InitController()
    {
        base.InitController();
        //Debug.Log("RoomController Init");
    }

    /// <summary>
    /// 给玩家准备房间
    /// </summary>
    /// <param name="msg"></param>
    public void OnReadyRoom(MsgInfo msg)
    {
        var jsonData = JsonMapper.ToObject(msg.data);

        model.roomId = (int) jsonData["roomId"];

        var teamA = JsonMapper.ToObject<List<MatchPlayer>>(jsonData["teamA"].ToJson());
        var teamB = JsonMapper.ToObject<List<MatchPlayer>>(jsonData["teamB"].ToJson());
        List<MatchPlayer> readyRoomPlayer = teamA;
        readyRoomPlayer.AddRange(teamB);
        model.readyRoomPlayer = readyRoomPlayer;

        ui.Open(WindowName.Room);
        ui.DestoryWindow(WindowName.Group);
        ui.ClosePopUp(WindowName.Match);
    }


    /// <summary>
    /// 玩家发送确认请求
    /// </summary>
    public void OnConfirmRoom()
    {
        SendByTcp(RequestType.CONFIRM_ROOM, new RoomRequest()
        {
            roomId = model.roomId,
            type = (int) RequestType.CONFIRM_ROOM
        });
        
        SendByKcp(RequestType.JOIN_ROOM, new RoomRequest()
        {
            roomId = model.roomId
        });
        
        SendByWebSocket(RequestType.JOIN_ROOM, new RoomRequest()
        {
            roomId = model.roomId
        });

    }

    /// <summary>
    /// 取消房间
    /// </summary>
    public void OnCancelRoom()
    {
        SendByTcp(RequestType.CANCEL_ROOM, new RoomRequest()
        {
            roomId = model.roomId,
            type = (int) RequestType.CANCEL_ROOM
        });

        model.readyRoomPlayer = new List<MatchPlayer>();
        model.roomId = Constants.NUM_ZERO;
        
        ui.Open(WindowName.Lobby);
        ui.DestoryWindow(WindowName.Room);
    }
    
    
    /// <summary>
    /// 更新房间的玩家信息、将玩家加入房间，为以后在游戏中发送玩家的坐标、方向等做准备
    /// </summary>
    /// <param name="msg"></param>
    public void OnUpdateRoom(MsgInfo msg)
    {
        var response = JsonMapper.ToObject<RoomResponse>(msg.data);
        model.UpdateRoomReadyInfo(response.channelId);
        roomWindow.OnUpdateRoom(response);
    }
}
